`timescale 1ns / 1ps

module add( 
input clk,//系统时钟 
input rst_n,//系统复位，低电平有效 
input [3:0] i_data,//数据输入口（最高位是符号位）大小：-8~+7范围有符号数 
input valid,//数据有效（高有效） 
output [5:0] o_data,//输出数据口（最高位是符号位） 
output o_ready//输出数据有效 
); 

reg signed [3:0] num0=0;
reg signed [3:0] num1=0;
reg signed [3:0] num2=0;
reg signed [3:0] num3=0;
reg [1:0] count=0;
reg [0:0] o_ready_reg;

//控制计数器
always @(posedge clk or negedge rst_n) begin
    if (!rst_n)begin
        count<=0;
    end
    else begin
        if(count>2)begin
            count <=0;
            o_ready_reg <= 1; 
        end     
        else
            if(valid)begin
                count <= count + 1;
                o_ready_reg <= 0;
            end    
            else
                begin
                    count <= count;
                    o_ready_reg <= 0;
            end                   
    end
end

always  @(posedge clk or negedge rst_n) begin
    if (!rst_n)begin
        num0<=0;
        num1<=0;
        num2<=0;
        num3<=0;
    end
    else begin
        if (valid)begin
            case(count)
                0:num0<=i_data;
                1:num1<=i_data;
                2:num2<=i_data;
                3:num3<=i_data;
                default: begin
                    num0<=num0;
                    num1<=num1;
                    num2<=num2;
                    num3<=num3;
                end 
            endcase
        end
        else begin
            num0<=num0;
            num1<=num1;
            num2<=num2;
            num3<=num3;
        end
    end
end

assign o_ready = o_ready_reg;
assign o_data =  o_ready ? num0+num1+num2+num3 : 0;

endmodule
